package com.nowcoder.community.controller;

import com.nowcoder.community.entity.Event;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.event.EventProducer;
import com.nowcoder.community.service.LikeService;
import com.nowcoder.community.utils.CommonUtil;
import com.nowcoder.community.utils.ConstantUtil;
import com.nowcoder.community.utils.HostHolder;
import com.nowcoder.community.utils.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: shuhuang
 * @description:
 * @Date: 2022/11/22 21:22
 * @Version java version 1.8
 */
@Controller
public class LikeController {
    @Autowired
    private LikeService likeService;
    @Autowired
    private HostHolder hostHolder;
    @Autowired
    private EventProducer eventProducer;
    @Autowired
    private RedisTemplate redisTemplate;

    /*
     *点赞功能
     * @todo:之后再来实现对登录后的人才能点赞，没登录则不可以的权限控制
     */
    @PostMapping(path = "/like")
    @ResponseBody
    public String like(int entityType, int entityId, int entityUserId, Integer discussPostId) {
        User user = hostHolder.getUser();
        if (user != null) {
            //点赞
            likeService.like(user.getId(), entityType, entityId, entityUserId);
            //数量
            long likeCount = likeService.findEntityLikeCount(entityType, entityId);
            //状态
            int likeStatus = likeService.findEntityLikeStatus(user.getId(), entityType, entityId);
            //返回结果
            Map<String, Object> map = new HashMap<>();
            map.put("likeCount", likeCount);
            map.put("likeStatus", likeStatus);

            //触发的点赞事件
            if (likeStatus == 1) {
                Event event = new Event()
                        .setTopic(ConstantUtil.TOPIC_LIKE)
                        .setUserId(hostHolder.getUser().getId())
                        .setEntityType(entityType)
                        .setEntityId(entityId)
                        .setEntityUserId(entityUserId)
                        .setData("postId", discussPostId);
                eventProducer.fireEvent(event);
            }

            if (entityType == ConstantUtil.ENTITY_TYPE_POST) {
                //计算帖子分数
                String postScoreKey = RedisKeyUtil.getPostScoreKey();
                redisTemplate.opsForSet().add(postScoreKey, discussPostId);
            }

            return CommonUtil.getJSONString(0, "请求成功！", map);
        } else {
            return CommonUtil.getJSONString(1, "您还没有登录，请先登录哦~");
        }
    }
}
